package middleware

import (
	"fmt"
	"net/http"
	"strings"

	"codeberg.org/vnpower/pixivfe/v2/server/session"
)

// SetPrivacyHeaders is a middleware that adds security headers to HTTP responses.
func SetPrivacyHeaders(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		header := w.Header()
		header.Add("Referrer-Policy", "same-origin") // needed for settings redirect
		header.Add("X-Frame-Options", "DENY")
		// use this if need iframe: `X-Frame-Options: SAMEORIGIN`
		header.Add("X-Content-Type-Options", "nosniff")
		/*
			NOTE: The HSTS header is commented out to avoid potential conflicts with reverse proxies,
						which may already set their own HSTS policies. Generally, it is better for reverse proxies
						to manage HSTS than for the application (such as PixivFE) to handle it.

						An application shouldn't set HSTS by default because doing so can lead to issues
						in environments where not all subdomains support HTTPS.

						Specifically, using a long 'max-age' value along with 'includeSubDomains' and 'preload' creates
						a risk of making a domain name inaccessible. Browsers that enforce HSTS will expect all subdomains
						to use HTTPS and cache this behavior for the duration of the `max-age` period, thereby causing issues
						if a domain or its subdomains are unable to support TLS in the future.
		*/
		// header.Add("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload")
		// use this if need iframe: `frame-ancestors 'self'`
		header.Add("Permissions-Policy", "accelerometer=(), ambient-light-sensor=(), battery=(), camera=(), display-capture=(), document-domain=(), encrypted-media=(), execution-while-not-rendered=(), execution-while-out-of-viewport=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), navigation-override=(), payment=(), publickey-credentials-get=(), screen-wake-lock=(), sync-xhr=(), usb=(), web-share=(), xr-spatial-tracking=()")
		// TODO: remove style-src 'unsafe-inline'
		// NOTE: default-src 'self' is required for rel="prefetch" to work on Firefox
		if !strings.HasPrefix(r.URL.Path, "/diagnostics") {
			header.Add("Content-Security-Policy", fmt.Sprintf("base-uri 'self'; default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: %s; media-src 'self' %s; font-src 'self'; connect-src 'self'; form-action 'self'; frame-ancestors 'none';", session.GetImageProxyOrigin(r), session.GetImageProxyOrigin(r)))
		}
		h.ServeHTTP(w, r)
	})
}
